package com.neo.tiny.admin.service.sys.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.tiny.admin.mapper.sys.SysRoleMenuMapper;
import com.neo.tiny.admin.service.sys.SysRoleMenuService;
import com.neo.tiny.common.constant.CacheConstants;
import com.neo.tiny.admin.entity.sys.SysRoleMenu;
import com.neo.tiny.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yqz
 * @Description
 * @CreateDate 2022/8/8 15:12
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private CacheManager cacheManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveRoleMenu(Long roleId, String menusIds) {
        // 删除关系
        this.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, roleId));

        if (StrUtil.isBlank(menusIds)) {
            return Boolean.TRUE;
        }

        List<SysRoleMenu> roleMenuList = Arrays.stream(menusIds.split(StrUtil.COMMA)).map(menuId -> {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(Long.valueOf(menuId));
            return roleMenu;
        }).collect(Collectors.toList());

        // 由于菜单相关数据都在用户信息缓存，所以此时需要清空缓存
        Set<String> keys = redisService.keys(CacheConstants.USER_DETAILS + StrUtil.COLON + CacheConstants.CACHE_PATTERN_PREFIX);
        redisService.del(keys);
        // 清空userinfo
        return this.saveBatch(roleMenuList);
    }
}
